<?php
namespace App\Http\Controllers\Api\v1;

use App\Cate as CateModel;
use App\Http\Controllers\Api\BaseController;
use App\Http\Requests\CateRequest;
use App\Http\Resources\Cate;
use App\Http\Resources\CateCollection;
use App\Repositories\CateRepository;
use App\Scopes\StatusScope;
use App\Traits\BaseApiFunc;
use Auth;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;

class CateController extends BaseController {

	use BaseApiFunc;

	protected $model, $page_size;

	public function __construct(CateRepository $cate) {
		parent::__construct();

		$this->model = $cate;
		$this->page_size = config('blog.admin_page.cate_page');
	}

	public function cates() {
		$list = Cache::remember('cates', config('blog.cache.time'), function () {
			return $this->model->select('id', 'cate_name')->withCount(['items' => function ($query) {
				return $query->where('status', 1);
			}])->limit(12)->get();
		});
		return $this->response->withSuccess($list);
	}

	public function store(CateRequest $request) {
		$this->model->store(array_merge(['user_id' => Auth::user()->id], $request->all()));
		return $this->response->withNoContent();
	}

	public function all() {
		$list = $this->model->select('id', 'cate_name', 'status')->withoutGlobalScope(StatusScope::class)->get();
		return $this->response->withSuccess($list);
	}

	protected function getResourceCollection(Collection $collection): CateCollection {
		return new CateCollection($collection->load(['items' => function ($query) {
			return $query->withoutGlobalScope(StatusScope::class);
		}]));
	}

	protected function getResource(CateModel $collection): Cate {
		return new Cate($collection);
	}
}
